package com.haochu.novel.util;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.haochu.novel.util.Constants.DIRECTORY_TYPE;
import com.haochu.novel.vo.Book;
import com.haochu.novel.vo.Directory;

/**
 * @author fuhuichao
 * 2017年7月3日14:14:43
 * 文件工具类
 */
public class FileUtil {

	/**
	 * 搜索目录下的文件夹
	 */
	public static List<Directory> searchDirectory(String path, List<Book> books){
		List<Directory> list = new ArrayList<Directory>();
		File file = new File(path);
		if (file.exists()) {
			File[] files = file.listFiles();
			if(files != null){
				for (File f : files) {
					Directory directory = new Directory();
					directory.setName(f.getName());
					directory.setPath(f.getAbsolutePath());
					directory.setType(f.isDirectory() ? DIRECTORY_TYPE.dir : DIRECTORY_TYPE.file);
					directory.setExist(false);
					for(Book b : books){
						if(f.getName().equals(b.getName()) && f.getAbsolutePath().equals(b.getPath())){
							directory.setExist(true);
							break;
						}
					}
					list.add(directory);
				}
			}
		}
		
		// 排序
		Collections.sort(list, new Comparator<Directory>() {
			@Override
			public int compare(Directory d1, Directory d2) {
				if(d1.getType() == DIRECTORY_TYPE.file){
					return -1;
				}
				if(d2.getType() == DIRECTORY_TYPE.file){
					return 1;
				}
				return 0;
			}
		});
		
		return list;
	}
	
}
